<?php

namespace Api\Controller;

use Api\Library\Token;
use Think\Controller;
use Api\Library\Weixin;

class WxpayController extends PublicController
{
    //构造函数
    public function _initialize()
    {
        parent::_initialize();
        //php 判断http还是https
        $this->http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        vendor('WeiXinpay.wxpay');
    }

    /**
     * 微信支付接口
     * @return bool
     */
    public function wxpay()
    {
        $uId = intval($this->get("id"));
        if (!$uId) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }
        $order_id_arr = isset($_GET['order_id']) ? $_GET['order_id'] : 0;
        if (!$order_id_arr) {
            $this->json_error('no_such_order');
            return false;
        }
        //获取订单号
        $order_sn = !empty($_GET['order_sn']) ? $_GET['order_sn'] : null;
        if (empty($order_sn)) {
            $this->json_error("订单号不能为空！");
            exit;
        }
        //①、获取用户openid
        $openId = M('user')->where('id=' . $uId)->getField('openid');
        if (!$openId) {
            echo json_encode(array('status' => 0, 'err' => '用户状态异常！'));
            exit();
        }
        $order_ids = explode('|', $order_id_arr);
        $ids = $this->db_create_in($order_ids);
        $orders = M("order")->where('id ' . $ids)->select();
        $info = array();
        foreach ($orders as $key => $value) {
            $info['amount'] += floatval($value['amount']);
            $info['order_sn'][] = $value['order_sn'];
        }
        $order_info['amount'] = $info['amount'];
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("瑞斯美产品购买_" . trim($order_sn));
        $input->SetAttach("瑞斯美产品购买_" . trim($order_sn));
        $input->SetOut_trade_no($order_sn . "_" . (int)$order_info['amount']);
        $input->SetTotal_fee(floatval($order_info['amount']) * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
        $input->SetGoods_tag("瑞斯美产品购买_" . trim($order_sn));
        $input->SetNotify_url('https://ruism.gzgaodu.com/index.php/Api/Wxpay/notify');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $arr = array();
        $arr['appId'] = $order['appid'];
        $arr['nonceStr'] = $order['nonce_str'];
        $arr['package'] = "prepay_id=" . $order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = $this->ToUrlParams($arr);
        $jmstr = $str . "&key=" . \WxPayConfig::KEY;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        $this->savePackage($order_ids, $arr['package']);
        $this->json_result($arr);
        exit();
        //获取共享收货地址js函数参数
        //$editAddress = $tools->GetEditAddressParameters();
        //$this->assign('jsApiParameters',$jsApiParameters);
        //$this->assign('editAddress',$editAddress);
    }

    /**
     * 邮费支付
     *
     * @return bool
     */
    public function wxpay_postage()
    {
        $uId = intval($this->get("id"));
        if (!$uId) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }
        // 验证中奖id
        $award_id = isset($_GET['award_id']) ? $_GET['award_id'] : 0;
        if (!$award_id & M('user_award')->where('id=' . $award_id)->find()) {
            $this->json_error('no_such_award');
            return false;
        }

        // 获取用户openid
        $openId = M('user')->where('id=' . $uId)->getField('openid');
        if (!$openId) {
            echo json_encode(array('status' => 0, 'err' => '用户状态异常！'));
            exit();
        }

        $order_info['amount'] = 10;
        $order_sn = 'useraward_' . $award_id;
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("瑞斯美奖品邮费_" . trim($order_sn));
        $input->SetAttach("瑞斯美奖品邮费_" . trim($order_sn));
        $input->SetOut_trade_no($order_sn . "_" . (int)$order_info['amount']);
        $input->SetTotal_fee(floatval($order_info['amount']) * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
        $input->SetGoods_tag("瑞斯美奖品邮费_" . trim($order_sn));
        $input->SetNotify_url('https://ruism.gzgaodu.com/index.php/Api/Wxpay/notify');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $arr = array();
        $arr['appId'] = $order['appid'];
        $arr['nonceStr'] = $order['nonce_str'];
        $arr['package'] = "prepay_id=" . $order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = $this->ToUrlParams($arr);
        $jmstr = $str . "&key=" . \WxPayConfig::KEY;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        $this->json_result($arr);
        exit();
    }

    public function db_create_in($item_list, $field_name = '')
    {
        if (empty($item_list)) {
            return $field_name . " IN ('') ";
        } else {
            if (!is_array($item_list)) {
                $item_list = explode(',', $item_list);
                foreach ($item_list as $k => $v) {
                    $item_list[$k] = intval($v);
                }
            }
            $item_list = array_unique($item_list);
            $item_list_tmp = '';
            foreach ($item_list as $item) {
                if ($item !== '') {
                    $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
                }
            }
            if (empty($item_list_tmp)) {
                return $field_name . " IN ('') ";
            } else {
                return $field_name . ' IN (' . $item_list_tmp . ') ';
            }
        }
    }

    /**
     * 保存
     */
    public function savePackage($ids, $package)
    {
        foreach ($ids as $key => $value) {
            $sql = "update lr_order set package='$package' WHERE id=$value";
            M("order")->execute($sql);
        }
    }

    /**
     * 支付回调接口
     * @author tiedong
     * @date 2018-01-25
     */
    public function notify()
    {
        /*$notify = new \PayNotifyCallBack();
        $notify->Handle(false);*/

        $res_xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $ret = json_decode(json_encode(simplexml_load_string($res_xml, 'simpleXMLElement', LIBXML_NOCDATA)), true);

        $path = "./Data/log/";
        if (!is_dir($path)) {
            mkdir($path, 0777);  // 创建文件夹test,并给777的权限（所有权限）
        }
        $content = date("Y-m-d H:i:s") . '=>' . json_encode($ret);  // 写入的内容
        $file = $path . "weixin_" . date("Ymd") . ".log";    // 写入的文件
        file_put_contents($file, $content, FILE_APPEND);  // 最简单的快速的以追加的方式写入写入方法，

        $data = array();
        $data['order_sn'] = $ret['out_trade_no'];
        $data['pay_type'] = 'weixin';
        $data['trade_no'] = $ret['transaction_id'];
        $data['total_fee'] = $ret['total_fee'];
        $result = $this->orderhandle($data);
        if (is_array($result)) {
            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml .= "</xml>";
            echo $xml;
        } else {
            $contents = 'error => ' . json_encode($result);  // 写入的内容
            $files = $path . "error_" . date("Ymd") . ".log";    // 写入的文件
            file_put_contents($files, $contents, FILE_APPEND);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }

    //***************************
    //  订单处理 接口
    //***************************
    public function orderhandle($data)
    {
        // 邮费支付
        if (strpos($data['order_sn'], 'useraward_') !== false) {
            $awardId = explode('_', $data['order_sn']);
            $awardId = $awardId[1];
            $award_info = M('user_award')->where('id=' . $awardId)->find();
            if (!$award_info) {
                return "邮费支付id信息错误...";
            }
            $sql = 'update lr_user_award set postage=1 where id = ' . $awardId;
            $result = M("user_award")->execute($sql);
            exit;
        }

        //$order_sn = trim($data['order_sn']);
        $pay_type = trim($data['pay_type']);
        $trade_no = trim($data['trade_no']);
        $total_fee = floatval($data['total_fee']);
        $outTradeNoArray = explode('_', $data['order_sn']);
        $out_trade_nos = $outTradeNoArray[0];
        $map['order_sn'] = ["like", "%$out_trade_nos%"];
        $order_infos = M('order')->where($map)->select();
        if (!is_array($order_infos) && count($order_infos)) {
            return "订单信息错误...";
        }
        foreach ($order_infos as $key => $value) {
            if ($value['status'] < 10 || $value['back'] > '0') {
                return "订单异常...";
            }
            $up = array();
            $up['type'] = $pay_type;
            //$up['price_h'] = sprintf("%.2f",floatval($total_fee/100));
            $up['status'] = 20;
            $up['trade_no'] = $trade_no;
            M('order')->where('order_sn="' . $value['order_sn'] . '"')->save($up);
        }
    }

    //构建字符串
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 模板消息的推送
     * @author tiedong
     * @date 2018-02-06
     */
    public function tuiNews()
    {
        $accessToekn = $this->getAccrssToken();
        $news = new Weixin($accessToekn);
        $data = $this->getNews();
        $result = $news->getTemplateMessage($data);
        var_dump($result);
    }

    /**
     * 获取access_token
     * @author tiedong
     * @date 2018-02-06
     */
    public function getAccrssToken()
    {
        $get_weixin = C("weixin");
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $get_weixin['appid'] . '&secret=' . $get_weixin['secret'];
        $html = file_get_contents($url);
        $output = json_decode($html, true);
        $access_token = $output['access_token'];
        return $access_token;
    }

    /**
     * 构建模板消息
     * @author tiedong
     * @date 2018-02-06
     */
    public function getNews()
    {
        $data = <<<END
        {
          "touser": "ofiz50ELLUscsrmuoRIqo7Csfvqw",  
          "template_id": "sVPWdagQZNrOttGb0zHuuauH_WpYOxseqoQ4PJE2pWA", 
          "page": "index",          
          "form_id": "wx201802051823401751a2c1740206974685",         
          "data": {
              "keyword1": {
                  "value": "2015年01月05日 12:30", 
                  "color": "#173177"
              }, 
              "keyword2": {
                  "value": "粤海喜来登酒店", 
                  "color": "#173177"
              }, 
              "keyword3": {
                  "value": "1235566", 
                  "color": "#173177"
              } , 
              "keyword4": {
                  "value": "10", 
                  "color": "#173177"
              } 
          },
          "emphasis_keyword": "keyword1.DATA" 
        }
END;
        return $data;

    }

    public function shiToken()
    {
        $token = "myToken";
        $token = new Token($token);
        $token->isValid();
    }

}

?>